<template>
  <div>
    <el-form
      ref="elFrom"
      :hide-required-asterisk="true"
      :label-width="labelwidth"
      :model="formdata"
      :rules="rules"
      style="width: auto"
      v-bind="$attrs"
    >
      <slot name="zfrombefore"></slot>
      <!--            {{formdata}}-->
      <component :is="$attrs.inline ? 'span' : 'el-row'" :gutter="8">
        <component
          :is="$attrs.inline ? 'span' : 'el-col'"
          v-for="(item, index) in inputsxs"
          :key="index"
          :class="{ span12: item.span == 12 || Number(colspan) == 12 }"
          :span="item.span ? Number(item.span) : Number(colspan)"
        >
          <!-- {{ formdata[item.value] }}{{ item.value }}{{ formdata.sjfhyj }} -->
          <slot :formdata="formdata" :item="item" :name="item.value">
            <template v-if="item.type == 'utel'">
              <el-form-item label="预留电话" status-icon>
                <el-input v-model="USearchutelxs" :readonly="true">
                  <template #append>
                    <el-button :loading="WpassSmsloding" @click="WpassSmsfn">
                      {{ WpassSmstext }}
                    </el-button>
                  </template>
                </el-input>
              </el-form-item>
              <el-form-item label="验证码" prop="yzm" status-icon>
                <el-input v-model="formdata.yzm" />
              </el-form-item>
            </template>
            <el-form-item
              v-else
              :label="item.label"
              :label-width="item.labelwidth"
              :prop="item.value"
              status-icon
            >
              <zup-img
                v-if="item.type == 'imgs'"
                :imgdata="formdata"
                :input="item"
                @setimgs="setimgs"
              />
              <el-button
                v-else-if="item.type == 'wangeditor'"
                class="wangeditorbutton"
                @click="btnclickfn(item)"
              >
                <el-scrollbar style="height: 276px">
                  <div :innerHTML="formdata[item.value]"></div>
                </el-scrollbar>
              </el-button>
              <el-switch
                v-else-if="item.type == 'switch'"
                v-model="formdata[item.value]"
                active-value="1"
                :disabled="item.disabled"
                inactive-value="0"
                :readonly="item.readonly"
              />
              <!--  -->
              <div v-else-if="item.type == 'radio'">
                <el-radio
                  v-for="(radioitem, radiokey) in item.option"
                  :key="radiokey"
                  v-model="formdata[item.value]"
                  :disabled="item.disabled"
                  :label="radioitem.value"
                  size="large"
                >
                  {{ radioitem.label }}
                </el-radio>
              </div>
              <el-input
                v-else-if="item.type == 'pcs'"
                v-model="formdata[item.value + 'lookstr']"
                :disabled="item.disabled"
                readonly="readonly"
                style="
                  width: 100%;
                  min-width: 200px;
                  background: none;
                  color: #ffffff;
                "
                @click="pcsshowfn(item)"
              />
              <el-select
                v-else-if="item.type == 'select'"
                v-model="formdata[item.value]"
                :disabled="item.disabled"
                filterable
                :placeholder="item.placeholder ? item.placeholder : '请选择'"
              >
                <el-option
                  v-for="itemoptions in optionsfn(item, formdata)"
                  :key="itemoptions.value"
                  :label="itemoptions.label"
                  :value="itemoptions.value"
                />
              </el-select>
              <formexcel
                v-else-if="item.type == 'excel'"
                :disabled="item.disabled"
                :input="item"
                :readonly="item.readonly"
                @setexcel="setexcel"
              />
              <!--                    lx58time-->
              <el-time-select
                v-else-if="item.type == 'lx58time'"
                v-model="formdata[item.value]"
                :clearable="false"
                end="24:00"
                :placeholder="item.placeholder"
                start="00:00"
                step="00:01"
              />
              <el-date-picker
                v-else-if="item.type == 'datetimerange'"
                v-model="formdata[item.value]"
                :clearable="false"
                :disabled-date="item.disabledDate"
                :end-placeholder="
                  item.endplaceholder ? item.endplaceholder : '结束日期'
                "
                :placeholder="item.placeholder"
                :range-separator="
                  item.rangeseparator ? item.rangeseparator : '至'
                "
                :shortcuts="shortcutsfn(item.shortcuts)"
                :start-placeholder="
                  item.startplaceholder ? item.startplaceholder : '开始日期'
                "
                style="width: 100%"
                :type="item.itemtype ? item.itemtype : 'datetimerange'"
              />
              <el-input
                v-else
                v-model="formdata[item.value]"
                :disabled="item.disabled"
                :placeholder="item.placeholder"
                :readonly="item.readonly"
              >
                <template #append v-if="item.type == 'mpt'">
                  <el-button
                    icon="el-icon-map-location"
                    @click="btnclickfn(item)"
                  />
                </template>
                <template #append v-else-if="item.dw">
                  {{ item.dw }}
                </template>
              </el-input>
            </el-form-item>
          </slot>
        </component>
      </component>

      <slot name="zfromafter"></slot>
    </el-form>

    <formpcs ref="pcsdialog" title="区域选择">
      <span class="dialog-footer">
        <el-button @click="$refs['pcsdialog'].showEdit(false)">取消</el-button>
        <el-button type="primary" @click="pcsqdfn">确定</el-button>
      </span>
    </formpcs>
    <zmap-box
      v-if="mptdialogVisible"
      v-model="mptdialogVisible"
      :markerpoint="markerpoint"
      title="地址"
      width="600px"
    >
      <template #default="scope">
        <span class="dialog-footer">
          <el-button @click="mptdialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="mptqdfn(scope)">确 定</el-button>
        </span>
      </template>
    </zmap-box>
  </div>
</template>
<script>
  import zmapBox from '@/components/zFrom/zmapBox'
  import zupImg from '@/components/zFrom/zupImg'
  import formpcs from '@/components/formpcs/index'
  import formexcel from '@/components/formexcel/index'

  import { ElMessage } from 'element-plus'
  export default {
    components: {
      zmapBox,
      zupImg,
      formpcs,
      formexcel,
      // zwangEditor
    },
    props: {
      nowinputs: {
        default: [],
      },
      nowdata: {
        default: {},
      },
      colspan: {
        type: [Number, String],
        default: 24,
      },
      labelwidth: {
        type: String,
        default: '80px',
      },
    },
    data() {
      return {
        firstName: 'Denny',
        lastName: 'Zhang',
        num: 1,
        formdata: {},
        // inputsxs:[],
        data: {},
        // rules: {},
        mptdialogVisible: false,

        markerpoint: 'POINT(120.119221 30.345277)',

        dqinput: {},

        imglist: [],
        worddialogVisible: false,
        wordhtml: '',

        USearchutel: '',
        USearchutelxs: '',
        WpassSmstext: '获取验证码',
        WpassSmsloding: false,
        WpassSmspar: 'Notel',
        setitem: {},
        //
        // this.$store.state.USearch
      }
    },
    computed: {
      rules() {
        this.$nextTick(() => {
          this.$refs.elFrom.clearValidate()
        })
        if (!this.inputsxs) {
          return {}
        }
        let r = {}
        r.yzm = [
          {
            validator: (rule, value, callback) => {
              if (value == '' || value.length != 6) {
                callback(new Error('error'))
              } else {
                callback()
              }
              // return v == this.WpassSmspar
            },
            trigger: 'blur',
            message: '验证码错误',
          },
        ]
        this.inputsxs.forEach((e) => {
          if (e.rule) {
            r[e.value] = e.rule
          }
        })
        return r
      },
      inputsxs() {
        let frominput = this.nowinputs.filter((f) => {
          if (f['if']) {
            if (typeof f['if'] == 'object') {
              let r = f['if'].find((fif) => {
                if (typeof fif == 'function') {
                  let ifdata = fif()
                  if (!ifdata) {
                    return true
                  }
                }
                let zhi = this.formdata[fif['value']]
                  ? this.formdata[fif['value']]
                  : ''
                fif['zhi'] = fif['zhi'] ? fif['zhi'] : []
                fif['nozhi'] = fif['nozhi'] ? fif['nozhi'] : []
                let nozhifalg =
                  fif['nozhi'].indexOf(this.formdata[fif['value']]) >= 0
                if (nozhifalg) {
                  return true
                } else if (fif['zhi'].length == 0) {
                  return false
                }
                return fif['zhi'].indexOf(zhi) < 0
              })
              return !r
            } else if (typeof f['if'] == 'string') {
              return f['zhi'].indexOf(this.formdata[f['if']]) >= 0
            } else {
              return true
            }
          } else {
            return true
          }
        })
        frominput = frominput.map((e) => {
          if (e.type == 'imgs') {
            e.values = e.values ? e.values : [e.value]
          }
          return e
        })
        // this.rulesfn(frominput);
        return frominput
      },
    },
    watch: {
      formdata: {
        handler: function () {
          this.$emit('change')
        },
        deep: true,
      },
      nowdata: {
        handler: function () {
          this.settingfn()
        },
        deep: true,
      },
      nowinputs: {
        handler: function () {
          this.settingfn()
        },
        deep: true,
      },
      inputsxs: function (nvalue, ovalue) {
        let n = new Set(nvalue)
        let o = new Set(ovalue)
        let edtinputs = new Set(
          [...n].filter((e) => {
            return !o.has(e)
          })
        )
        if (edtinputs.size == 0) {
          return
        }
        ;[...edtinputs].forEach((e) => {
          this.setformdatafn(e, this.formdata)
        })
      },
    },
    mounted() {
      this.USearchutel = this.$store.state.user.USearch.utel
      this.USearchutelxs =
        this.USearchutel.length >= 7
          ? `${this.USearchutel.slice(0, 3)}****${this.USearchutel.slice(
              7,
              this.USearchutel.length
            )}`
          : this.USearchutel
      this.settingfn()
    },
    methods: {
      setexcel({ value, input }) {
        this.formdata[input.value] = value
        this.$refs.elFrom.validateField(input.value)
      },
      shortcutsfn(data = []) {
        let r = this.$z.deepClone(data)
        return r
      },
      async pcsqdfn() {
        this.$refs['pcsdialog'].showEdit(false)
        let data = this.$refs['pcsdialog'].getCurrentNode()
        if (!data) {
          data = { id: '' }
        }
        this.formdata[this.setitem.value] = data.id
        this.formdata[this.setitem.value + 'lookstr'] = await this.pcsvaluefn(
          this.setitem
        )
        this.$emit('setpcs', data)
        this.$refs.elFrom.clearValidate(this.setitem.value)
      },
      pcsshowfn(item = {}) {
        this.setitem = item
        // item.all=true
        this.$refs['pcsdialog'].showEdit(
          true,
          this.setitem,
          this.formdata[this.setitem.value]
        )
      },
      WpassSmsfn() {
        if (this.USearchutel == '') {
          this.$message.error('联系方式错误')
          return
        }
        this.WpassSmsloding = true
        this.$z.$axios
          .post('/WpassSms', { utel: this.USearchutel })
          .then((reqdata) => {
            let { data } = reqdata
            if (data[0].par == 'Notel') {
              alert('获取验证码失败')
            } else {
              let ddtime = 60
              this.WpassSmstext = '已发送(' + ddtime + 's)'
              let yzmsetinter = setInterval(() => {
                ddtime--
                if (ddtime <= 0) {
                  this.WpassSmstext = '重新发送'
                  this.WpassSmsloding = false
                  clearTimeout(yzmsetinter)
                  return false
                }
                this.WpassSmstext = '已发送(' + ddtime + 's)'
              }, 1000)

              this.WpassSmspar = data[0].par
            }
          })
      },
      async settingfn() {
        this.data = this.$z.deepClone(this.nowdata)
        this.formdata = await this.setformdatasfn()
      },
      async setformdatasfn() {
        let r = this.$z.deepClone(this.nowdata)
        if (!this.inputsxs) {
          return r
        }
        this.inputsxs.forEach(async (e) => {
          if (e.fl && r[e.value]) {
            r[e.value] = this.$z.math.divide(r[e.value], e.fl).toString()
          } else if (e.type == 'mpt') {
            r[e.mptzd] = r[e.mptzd] ? r[e.mptzd] : 'POINT(120.119221 30.345277)'
          } else if (
            typeof r[e.value] != 'undefined' &&
            typeof r[e.value] != 'string' &&
            typeof r[e.value] != 'object'
          ) {
            r[e.value] = r[e.value].toString()
          } else if (typeof e.defaultValue != 'undefined') {
            if (r[e.value] == '' || !r[e.value]) {
              r[e.value] = e.defaultValue.toString()
            }
          } else if (typeof r[e.value] == 'undefined') {
            r[e.value] = ''
          }
          if (e.type == 'pcs') {
            r[e.value + 'lookstr'] = await this.pcsvaluefn(e, r)
          }
        })
        return r
      },
      async pcsvaluefn(item, data = this.formdata) {
        let str = String(data[item.value])
        if (!str || str == '') {
          str = item.defaultText ? item.defaultText : '全部'
        } else {
          let array = str.split(','),
            pcss = []
          for (let index = 0; index < array.length; index++) {
            const element = array[index]
            let stationdata = await this.$store.dispatch(
              'stationnew/getstationone',
              element
            )
            pcss = pcss.concat(stationdata)
          }

          str = pcss
            .map((e) => {
              return e.pcs
            })
            .join()
        }
        return str
      },
      setformdatafn(e = {}, r = {}) {
        if (
          e.bindingzd &&
          typeof e.bindingzd == 'object' &&
          this.$attrs[e.bindingzd.attr] &&
          typeof this.$attrs[e.bindingzd.attr][e.bindingzd.zd] != 'undefined'
        ) {
          let rstr = this.$attrs[e.bindingzd.attr][e.bindingzd.zd]

          if (e.fl && rstr) {
            rstr = this.$z.math.divide(rstr, e.fl).toString()
          }
          r[e.value] = rstr
        } else if (e.type == 'mpt') {
          r[e.mptzd] = r[e.mptzd] ? r[e.mptzd] : 'POINT(120.119221 30.345277)'
        } else if (typeof e.defaultValue != 'undefined') {
          r[e.value] = e.defaultValue.toString()
        } else if (typeof r[e.value] == 'undefined') {
          r[e.value] = ''
        } else {
          r[e.value] = ''
        }
      },
      rulesfn(frominput = this.inputsxs) {
        this.rules = {}
        this.rules.yzm = [
          {
            validator: (e, v) => {
              return v == this.WpassSmspar
            },
            trigger: 'blur',
            message: '验证码错误',
          },
        ]
        frominput.forEach((e) => {
          if (e.rule) {
            this.rules[e.value] = e.rule
          }
        })
      },
      async setnowdatafn() {
        let r = this.$z.deepClone(this.formdata)
        let array = this.inputsxs
        for (let index = 0; index < array.length; index++) {
          const e = array[index]
          let val = this.formdata[e.value]
          if (e.type == 'utel') {
            let par = await this.$z.$axios.post('/WpassSmsChk', {
              utel: this.$store.state.user.USearch.utel,
              sms: val,
            })
            par = par.data
            if (par[0].par != 'succeed') {
              ElMessage.error('验证码错误')
              return Promise.reject()
            }
            r[e.value] = val
          } else if (e.type == 'datetimerange') {
            if (e.itemtype == 'datetimerange' || !e.itemtype) {
              e.values = e.values ? e.values : []
              if (e.values.length != 0) {
                r[e.values[0]] = this.$z.timeFormat(
                  val[0],
                  'yyyy-mm-dd hh:MM:ss'
                )
                r[e.values[1]] = this.$z.timeFormat(
                  val[1],
                  'yyyy-mm-dd hh:MM:ss'
                )
              }
            } else {
              if (val == '') {
                r[e.value] = val
              } else {
                r[e.value] = this.$z.timeFormat(val, 'yyyy-mm-dd')
              }
            }
          } else if (e.fl && r[e.value]) {
            r[e.value] = this.$z.math.multiply(r[e.value], e.fl)
          }
        }

        this.data = r
        return r
      },
      btnclickfn(item) {
        switch (item.type) {
          case 'mpt':
            this.dqinput = item
            this.mptdialogVisible = true
            this.markerpoint = this.formdata[item.mptzd]
            break
          case 'wangeditor':
            this.dqinput = item
            this.worddialogVisible = true
            this.wordhtml = this.formdata[item.value]
            break
        }
      },
      mptqdfn(scope) {
        this.formdata[this.dqinput.mptzd] = scope.mpt
        this.formdata[this.dqinput.value] = scope.dz
        this.mptdialogVisible = false
      },
      wordhtmlfn(scope) {
        this.formdata[this.dqinput.value] = scope.wordhtml.html
        this.worddialogVisible = false
      },
      validate() {
        return new Promise((resolve) => {
          this.$refs.elFrom.validate(async (valid) => {
            if (valid) {
              let v = await this.setnowdatafn()
              resolve(v)
            } else {
              // reject();
            }
          })
        })
      },
      setimgs(input, imglist) {
        input.values.forEach((e, i) => {
          this.formdata[e] = imglist[i] ? imglist[i].url : ''
        })
      },
      optionsfn(item) {
        let options = item.option ? item.option : []
        options = options.filter((e) => {
          if (typeof e.if == 'string') {
            e.zhi = e.zhi ? e.zhi : []
            e.nozhi = e.nozhi ? e.nozhi : []
            let rno = e.nozhi.indexOf(this.formdata[e.if]) >= 0
            if (rno) {
              return false
            }

            if (e.zhi.length == 0) {
              return true
            }
            return e.zhi.indexOf(this.formdata[e.if]) >= 0
          } else if (typeof e.if == 'object' && e.if.length != 0) {
            return e.if.find((f) => {
              return f.zhi.find((zhif) => {
                return this.formdata[f.zd] == zhif
              })
            })
          } else if (typeof e.if == 'function') {
            return e.if()
          } else {
            return true
          }
        })
        // if (!options.find((f) => {
        //     return this.formdata[item.value] == f.value
        // }) && options.length != 0) {
        //     this.formdata[item.value] = item.defaultValue ? item.defaultValue : options[0].value
        // }
        return options
      },
      validateField(prop) {
        // this.formdata
        return new Promise((resolve) => {
          this.$refs.elFrom.validateField(prop, (p) => {
            if (!p) {
              resolve(this.formdata[prop])
            }
          })
        })
        // return this.$refs.elForm.validateField();
      },
      forcesetformdatafn(data = {}) {
        for (let d in data) {
          this.formdata[d] = data[d]
        }
      },
    },
  }
</script>
<style lang="scss" scoped>
  .span12 .el-form-item {
    background: rgba(255, 255, 255, 0.2);
    margin-bottom: 8px;
    padding: 10px;
  }
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }

  .el-select {
    width: 100%;
  }

  .avatar-uploader .el-upload:hover {
    border-color: #409eff;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }

  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }

  .wangeditorbutton {
    width: 300px;
    text-align: left;
    max-height: 300px;

    img {
      width: 100% !important;
    }
  }
  .el-switch {
    float: right;
    margin-top: 10px;
  }
</style>
